package com.cy.pj.sys.service.impl;

import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysMenuDao sysMenuDao;

    /*重写此方法目的：底层对用户密码进行加密，需算法*/
    @Override
    public CredentialsMatcher getCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=
                new HashedCredentialsMatcher("MD5");
        credentialsMatcher.setHashIterations(1);
        return credentialsMatcher;
    }
//    public ShiroRealm(){
//        setCredentialsMatcher(new HashedCredentialsMatcher());
//    }



    /*获取并封装认证信息*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken= (UsernamePasswordToken)authenticationToken;
        //获取用户传入的用户名
        String username=upToken.getUsername();
        //在数据库内查找该用户
        SysUser user=sysUserDao.selectUserByUsername(username);
        if(user==null)
            throw new UnknownAccountException();
        if(user.getValid()==0)
            throw new LockedAccountException();
        //获取盐值，转换为ByteSource 等价于下方
        //ByteSource credentialsSalt= ByteSource.Util.bytes(user.getSalt());
        ByteSource credentialsSalt=new SimpleByteSource(user.getSalt());

        //用户信息，用于比对前端传入的密码
        return new SimpleAuthenticationInfo(
                user,//principal用户身份（基于业务设置）
                user.getPassword(),//hashedCredentials 已加密的凭证（密码）
                credentialsSalt, //获取盐值
                getName());//
    }


    /*获取并封装授权信息*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户
        SysUser user=(SysUser)principalCollection.getPrimaryPrincipal();

        //基于登录用户id，查询用户权限
        Set<String> permissionSet=
                sysMenuDao.selectUserPermissions(user.getId());

        //封装用户权限信息
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(permissionSet);
        return info;
    }
}
